package com.wanma;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ComparatorInArrayListStudy02 {
    public static void main(String[] args) {
    	//ArrayList<Object> list1 = new ArrayList<Object>(5000);
        ArrayList<Apple> list = new ArrayList<Apple>();
        list.add(new Apple(1, 81));
        list.add(new Apple(2, 76));
        list.add(new Apple(3, 91));
        list.add(new Apple(4, 84));
        list.add(new Apple(5, 79));
        list.add(new Apple(6, 87));
        list.add(new Apple(7, 85));
        list.add(new Apple(8, 83));
        list.add(new Apple(9, 91));
        System.out.println(list);//排序之前的list
        
        List<List<Apple>> disPartList = disPart(list,new Comparator<Apple>(){
            @Override
            public int compare(Apple o1, Apple o2) {//这里写具体的分组接口,分组方式可以使用对象内的属性的组合方式
                if(o1.getSize()/10 == o2.getSize()/10){//将苹果Apple按照size分组,每10个size分为一组
                    return 0;
                }
                return 1;
            }
        });
        for(List lis : disPartList){//分别遍历每一组
            System.out.println(lis);
        }
    }

    /**
     * 按照comparator进行分组的方法
     */
    public static <T> List<List<T>> disPart(List<T> list, Comparator<? super T> c) {
        ArrayList<List<T>> resultList = new ArrayList<List<T>>();
        for (T t : list) {
            boolean flag = false;
            for (int i = 0; i < resultList.size(); i++) {
                if (c.compare(t, resultList.get(i).get(0)) == 0) {// 若匹配成功则加入resultList中的子元素
                    flag = true;
                    resultList.get(i).add(t);
                    break;
                }
            }
            if (flag == false) {// 若flag为false则将此元素加入resultList为新元素
                List<T> listIn = new ArrayList<T>();
                listIn.add(t);
                resultList.add(listIn);
            }
        }
        return resultList;
    }
}